/*
 * Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
 *
 * https://www.mall4j.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */
package com.dlc.shop.platform.controller;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.PhoneUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.dlc.shop.bean.model.PlatformAddr;
import com.dlc.shop.common.annotation.SysLog;
import com.dlc.shop.common.config.Constant;
import com.dlc.shop.common.exception.YamiShopBindException;
import com.dlc.shop.common.i18n.I18nMessage;
import com.dlc.shop.common.response.ResponseEnum;
import com.dlc.shop.common.response.ServerResponseEntity;
import com.dlc.shop.common.util.PageParam;
import com.dlc.shop.common.util.PrincipalUtil;
import com.dlc.shop.service.PlatformAddrService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Objects;


/**
 * 平台地址库，用于国内收货地址和国外的发货地址
 * @author liyong
 */
@RestController
@RequestMapping("/platform/platformAddr")
@Tag(name = "平台地址库，用于国内收货地址和国外的发货地址")
@AllArgsConstructor
public class PlatformAddrController {

    private final PlatformAddrService platformAddrService;

    /**
     * 分页查询
     *
     * @param page       分页对象
     * @param platformAddr
     * @return 分页数据
     */
    @GetMapping("/page")
    @Operation(summary = "分页查询地址" , description = "分页查询地址")
    public ServerResponseEntity<IPage<PlatformAddr>> getPlatformAddrPage(PageParam<PlatformAddr> page, PlatformAddr platformAddr) {
        PageParam<PlatformAddr> platformAddrPageParam = platformAddrService.page(page, new LambdaQueryWrapper<PlatformAddr>()
                .eq(PlatformAddr::getShopId, 0)
                .ne(PlatformAddr::getStatus, -1).orderByDesc(PlatformAddr::getAddrId));
        if (CollUtil.isNotEmpty(platformAddrPageParam.getRecords())) {
            for (PlatformAddr record : platformAddrPageParam.getRecords()) {
                if (Objects.nonNull(record.getReceiverMobile())) {
                    record.setReceiverMobile(PhoneUtil.hideBetween(record.getReceiverMobile()).toString());
                }
                String tel = record.getReceiverTelephone();
                if (StrUtil.isNotBlank(tel)) {
                    String after = !tel.contains("-") ? tel : tel.split("-")[1];
                    String afterHide = PhoneUtil.hideBetween(after).toString();
                    String before = !tel.contains("-") ? "" : tel.split("-")[0] + "-";
                    record.setReceiverTelephone(before + afterHide);
                }
            }
        }
        return ServerResponseEntity.success(platformAddrPageParam);
    }


    /**
     * 通过id查询
     *
     * @param addrId id
     * @return 单个数据
     */
    @GetMapping("/info/{addrId}")
    @Operation(summary = "通过id查询地址" , description = "通过id查询地址")
    public ServerResponseEntity<PlatformAddr> getById(@PathVariable("addrId") Long addrId) {
        PlatformAddr platformAddr = platformAddrService.getById(addrId);
        if (Objects.nonNull(platformAddr.getReceiverMobile())) {
            platformAddr.setReceiverMobile(PhoneUtil.hideBetween(platformAddr.getReceiverMobile()).toString());
        }
        String tel = platformAddr.getReceiverTelephone();
        if (StrUtil.isNotBlank(tel)) {
            String after = !tel.contains("-") ? tel : tel.split("-")[1];
            String afterHide = PhoneUtil.hideBetween(after).toString();
            String before = !tel.contains("-") ? "" : tel.split("-")[0] + "-";
            platformAddr.setReceiverTelephone(before + afterHide);
        }
        return ServerResponseEntity.success(platformAddr);
    }

    /**
     * 新增
     *
     * @param
     * @return 是否新增成功
     */
    @SysLog("新增")
    @PostMapping
    @Operation(summary = "新增地址" , description = "新增地址")
    public ServerResponseEntity<Long> save(@RequestBody @Valid PlatformAddr platformAddr) {
        //Long shopId = SecurityUtils.getShopUser().getShopId();
        Date now = new Date();
        platformAddr.setShopId(Constant.PLATFORM_SHOP_ID);
        platformAddr.setCreateTime(now);
        platformAddr.setUpdateTime(now);
        // 添加成功
        return ServerResponseEntity.success(platformAddrService.addPlatformAddr(platformAddr));
    }

    /**
     * 修改
     *
     * @param platformAddr
     * @return 是否修改成功
     */
    @SysLog("修改")
    @PutMapping
    @Operation(summary = "修改地址" , description = "修改地址")
    public ServerResponseEntity<String> updateById(@RequestBody @Valid PlatformAddr platformAddr) {
        //Long shopId = SecurityUtils.getShopUser().getShopId();
        PlatformAddr dbPlatformAddr = platformAddrService.getById(platformAddr.getAddrId());
        if (Objects.isNull(dbPlatformAddr)) {
            throw new YamiShopBindException("yami.prod.common.invalid");
        }
        if (StrUtil.isNotBlank(platformAddr.getReceiverMobile()) && PrincipalUtil.isAsteriskMobile(platformAddr.getReceiverMobile())) {
            if (!PrincipalUtil.isDbPhone(platformAddr.getReceiverMobile(), dbPlatformAddr.getReceiverMobile(), false)) {
                throw new YamiShopBindException("yami.user.err.phone");
            }
            if (platformAddr.getReceiverMobile().contains(Constant.ASTERISK)) {
                platformAddr.setReceiverMobile(dbPlatformAddr.getReceiverMobile());
            }
        }
        if (StrUtil.isNotBlank(platformAddr.getReceiverTelephone()) && PrincipalUtil.isAsteriskTel(platformAddr.getReceiverTelephone())) {
            if (!PrincipalUtil.isDbPhone(platformAddr.getReceiverTelephone(), dbPlatformAddr.getReceiverTelephone(), true)) {
                throw new YamiShopBindException("yami.user.err.phone");
            }
            if (platformAddr.getReceiverTelephone().contains(Constant.ASTERISK)) {
                platformAddr.setReceiverTelephone(dbPlatformAddr.getReceiverTelephone());
            }
        }
        platformAddr.setUpdateTime(new Date());
        platformAddrService.updatePlatformAddr(Constant.PLATFORM_SHOP_ID, platformAddr);
        // 修改成功
        return ServerResponseEntity.success(ResponseEnum.SHOW_SUCCESS.value(), I18nMessage.getMessage("yami.activity.update.success"));
    }

    /**
     * 通过id删除
     *
     * @param addrId id
     * @return 是否删除成功
     */
    @SysLog("删除")
    @DeleteMapping("/{addrId}")
    @Operation(summary = "删除地址" , description = "删除地址")
    public ServerResponseEntity<Boolean> removeById(@PathVariable Long addrId) {
        return ServerResponseEntity.success(platformAddrService.removeById(addrId));
    }

    /**
     * 获取店铺的所有收获地址
     */
    @GetMapping("/list")
    @Operation(summary = "获取店铺的所有地址" , description = "获取店铺的所有地址")
    public ServerResponseEntity<List<PlatformAddr>> list() {
        //Long shopId = SecurityUtils.getShopUser().getShopId();
        List<PlatformAddr> list = platformAddrService.queryList();
        return ServerResponseEntity.success(list);
    }
}
